#include <stddef.h>
#include <string>
#include <stdlib.h>

#include "data/global_paramenter.h"
#include "data/db_struct.h"
#include "db/oracle_helper.h"
#include "db/virtual_db_helper.h"
#include "util/config_loader.h"

GlobalParam::GlobalParam()
{
    _modify = false;
    _database_helper = NULL;
    _login_log_list.Clean();
    _count_each_time = 0;
    _db_ip = "";
    _db_name = "";
    _db_account = "";
    _db_password = "";
}

GlobalParam::~GlobalParam()
{
    if (_database_helper != NULL)
        delete _database_helper;
}

bool GlobalParam::LoadFrom(const char* filename)
{
    bool ret = true;
    if (_config_loader.load_from("config.ini"))
    {
        _db_ip = _config_loader.get_value_of("DB_IP", "DB_INFO");
        if (_db_ip == "")
        {
            _db_ip = "127.0.0.1";
            _config_loader.set_value_of("DB_IP", "127.0.0.1", "DB_INFO");
            ret = false;
        }
        _db_name = _config_loader.get_value_of("Database", "DB_INFO");
        if (_db_name == "")
        {
            _db_name = "xe";
            _config_loader.set_value_of("Database", "xe", "DB_INFO");
            ret = false;
        }
        _db_account = _config_loader.get_value_of("Account", "DB_INFO");
        if (_db_account == "")
        {
            _db_account = "ppb";
            _config_loader.set_value_of("Account", "ppb", "DB_INFO");
            ret = false;
        }
        _db_password = _config_loader.get_value_of("Password", "DB_INFO");
        if (_db_password == "")
        {
            _db_password = "ppb";
            _config_loader.set_value_of("Password", "ppb", "DB_INFO");
            ret = false;
        }

        std::string count_each_time = _config_loader.get_value_of("COUNT_EACH_TIME", "LOGIN_LOG");
        if (count_each_time == "")
        {
            count_each_time = "500";
            _config_loader.set_value_of("COUNT_EACH_TIME", "500", "LOGIN_LOG");
            ret = false;
        }
        _count_each_time = atoi(count_each_time.c_str());
    }
    else
    {
        _db_ip = "127.0.0.1";
        _config_loader.set_value_of("DB_IP", "127.0.0.1", "DB_INFO");

        _db_name = "xe";
        _config_loader.set_value_of("Database", "xe", "DB_INFO");

        _db_account = "ppb";
        _config_loader.set_value_of("Account", "ppb", "DB_INFO");

        _db_password = "ppb";
        _config_loader.set_value_of("Password", "ppb", "DB_INFO");

        _count_each_time = 500;
        _config_loader.set_value_of("COUNT_EACH_TIME", "500", "LOGIN_LOG");
        ret = false;
    }
    _config_loader.save();
    return ret;
}

bool GlobalParam::Conn2DB()
{
    _database_helper = new OracleHelper();
//    _database_helper = new VirtualHelper();
    return _database_helper->connect(_db_ip.c_str(), _db_name.c_str(), _db_account.c_str(), _db_password.c_str());
}
